package cn.wolfcode.wolf2w.controller;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("users")
public class UserInfoController {

    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.appkey}")
    private String smsAppkey;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Autowired
    private IStrategyService strategyService;

    @RequireLogin
    @GetMapping("list")
    public Object list(){
        return userInfoService.selectAll();
    }

    //  验证手机号是否被注册
    @GetMapping("checkPhone")
    public Object checkPhone(String phone){
        boolean ret = userInfoService.findByPhone(phone);
        return !ret;
    }

    //  获取验证码
    @GetMapping("sendVerifyCode")
    public Object sendVerifyCode(String phone){
        userInfoService.sendVerifyCode(phone, smsUrl, smsAppkey);
        return JsonResult.success();
    }

    /**
     * phone
     * nickname
     * password
     * rpassword
     * verifyCode
     * @return
     */
    //  注册
    @PostMapping("regist")
    public Object regist(String phone, String nickname, String password, String rpassword, String verifyCode){
        userInfoService.regist(phone, nickname, password, rpassword, verifyCode);
        return JsonResult.success();
    }

    //  登录
    @PostMapping("login")
    public Object login(String username, String password){
        //  查询数据库的对象
        UserInfo user = userInfoService.login(username, password);

        //  把查询到的对象缓存到redis中
        String token = userInfoRedisService.setToken(user);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", user);

        return JsonResult.success(map);
    }

    //  重置存活时间
    @RequireLogin
    @GetMapping("currentUser")
    public Object currentUser(HttpServletRequest request){
        //  通过请求对象的getHeader("token")方法获取浏览器传入的token值
        String token = request.getHeader("token");

        //  通过token值，作为redis的key获取之前缓存redis里面的user对象
        UserInfo user = userInfoRedisService.getToken(token);

        //  判断user对象是否为null判断是否已经登录
        return JsonResult.success(user);
    }

    //  收藏操作
    @GetMapping("/strategies/favor")
    public Object strategiesFavor(String sid, String userId){
        return JsonResult.success(strategyService.queryStrategiesFavor(sid, userId));
    }
}
